package org.kalai.unifypay.tfb.pay;

import java.util.Map;
import java.util.TreeMap;

import org.apache.log4j.Logger;
import org.kalai.unifypay.Constant;
import org.kalai.unifypay.util.CommonUtil;
import org.kalai.unifypay.util.DateUtil;
import org.kalai.unifypay.util.HttpUtil;
import org.kalai.unifypay.util.StringUtil;

public final class TFBPay {

   private static final Logger logger             = Logger.getLogger(TFBPay.class);

   /**
    * 秘钥(MD5加密)
    */
   private static final String TFB_MD5_SECRET_KEY = Constant.TFB_MD5_SECRET_KEY;

   /**
    * 被扫支付
    * 
    */
   public static Map<String, Object> aliPayPayment(String tranxSN, long transAmt, String channelType, String commodityName,
         String payType,String returnUrl) {
      Map<String, Object> respMap = CommonUtil.createRespMap("XXXX", "验签失败");
      String result = "";
      TreeMap<String, Object> params = new TreeMap<String, Object>();
      params.put("spid", "1800776625");// 商户号
      params.put("notify_url", Constant.TFB_NOTIFY_URL);// 异步通知
      params.put("sp_billno", tranxSN);// 商户订单号
      params.put("spbill_create_ip", "101.67.156.243");// 商户ip
      params.put("pay_type", payType);// 支付类型(扫码支付:800201)
      params.put("tran_time", DateUtil.formatNow("yyyyMMddhhmmss"));// 发起交易时间
      params.put("tran_amt", transAmt);// 交易金额(单位为分)
      params.put("cur_type", "CNY");// 币种类型
      try {
         params.put("item_name",commodityName);// 订单标题
         String serviceUrl = "";
         /* 处理不同渠道请求参数 */
         switch (channelType) {
         case "ZFB_BS":
            serviceUrl = "http://apitest.tfb8.com/cgi-bin/v2.0/api_ali_pay_apply.cgi";
            break;
         case "WX_BS":
            serviceUrl = "http://apitest.tfb8.com/cgi-bin/v2.0/api_wx_pay_apply.cgi";
            params.put("bank_mch_name", "还呗科技");// 三级商户名称
            params.put("bank_mch_id", "5066902");// 三级商户ID
            break;
         case "WX_GZH":
            serviceUrl = "http://upay.tfb8.com/test/cgi-bin/v2.0/api_wx_subpay_apply.cgi";
            params.put("bank_mch_name", "还呗科技");// 三级商户名称
            params.put("bank_mch_id", "5066902");// 三级商户ID
            params.put("pay_show_url", "http://www.lechinepay.com");// 支付成功跳转URL
            break;
         default:
            return respMap = CommonUtil.createRespMap("XXXX", "渠道不存在");
         }

         // 加入协议参数
         TFBUtils.sign(params, TFB_MD5_SECRET_KEY);

         result = HttpUtil.sendHttpsPost(serviceUrl, params);
         
         /*如果是微信号支付直接返回支付中*/
         if(StringUtil.isNotEmpty(result)&&"WX_GZH".equals(channelType))
         {
            respMap = CommonUtil.createRespMap("00","公众号支付中");
            respMap.put("codeUrl", result);
            return respMap;
         }
         
         /* 验证返回信息签名 */
         TreeMap<String, String> resultMap = TFBUtils.xmlToMap(result);
         if (!TFBUtils.verifySign(resultMap, TFB_MD5_SECRET_KEY, resultMap.get("sign"))) {
            logger.error(String.format("(天付宝)返回信息签名失败:[result=%s]", result));
            return respMap;
         }
         String respCode = resultMap.get("retcode");
         String respMsg = resultMap.get("retmsg");
         respMap = CommonUtil.createRespMap(respCode.equals("0") ? "00" : respCode, respMsg);
         if (respCode.equals("00")) {
            respMap.put("respDesc", "订单创建成功");
            respMap.put("codeUrl", resultMap.get("qrcode"));
         } else {
            logger.error(String.format("(天付宝)支付失败:[params=%s]", params));
         }
      } catch (Exception e) {
         logger.error(String.format("(天付宝)支付异常:[params=%s]%s", params, e));
      }
      return respMap;
   }

   /**
    * 订单查询
    * 
    */
   public static Map<String, Object> queryOrder(String tranxSN) {
      Map<String, Object> respMap = CommonUtil.createRespMap("XXXX", "验签失败");
      TreeMap<String, Object> params = new TreeMap<String, Object>();
      params.put("spid", "1800776625");// 商户号
      params.put("sp_billno", tranxSN);// 商户订单号
      // 加入协议参数
      TFBUtils.sign(params, TFB_MD5_SECRET_KEY);

      String result = HttpUtil.sendHttpsPost("http://apitest.tfb8.com/cgi-bin/v2.0/api_ali_pay_qry.cgi", params);
      String a = TFBUtils.getXmlElement(result, "data");
      /* 验证返回信息签名 */
      TreeMap<String, String> resultMap = TFBUtils.xmlToMap(result);

      if (!TFBUtils.verifySign(resultMap, TFB_MD5_SECRET_KEY, resultMap.get("sign"))) {
         logger.error(String.format("(天付宝)返回信息签名失败:[resultMap=%s]", resultMap));
         return respMap;
      }
      String respCode = resultMap.get("retcode");
      String respMsg = resultMap.get("retmsg");
      respMap = CommonUtil.createRespMap(respCode.equals("0") ? "00" : respCode, respMsg);
      if (respCode.equals("00")) {
         respMap.put("respDesc", "订单创建成功");
         respMap.put("state", resultMap.get("state"));
      } else {
         logger.error(String.format("(天付宝)支付宝被扫支付失败:[resultMap=%s]", resultMap));
      }
      return respMap;
   }

   public static void main(String[] args) {
      // System.out.println(TFBPay.aliPayPayment("zsl_2016101915",
      // Constant.TFB_SERVICE_URL + "api_ali_pay_apply.cgi", 10, "zsl测试",
      // "800201").toString());
      // System.out.println(TFBPay.queryOrder("OR1019171352098733002"));
      String a = "<?xml version=\"1.0\" encoding=\"GB2312\" ?><root><data><record><close_time></close_time><create_time>2016-10-19 05:13:57</create_time><item_attach></item_attach><item_name>娴�璇�</item_name><listid>1021800776625161019000022342</listid><pay_time>2016-10-19 17:23:36</pay_time><pay_type>800201</pay_type><sp_billno>OR1019171352098733002</sp_billno><spid>1800776625</spid><state>3</state><tran_amt>20</tran_amt></record></data><retcode>00</retcode><retmsg>操作成功</retmsg><sign>4da2acff4f4d4fdc542aedd445a62902</sign><sign_type>MD5</sign_type><spid>1800776625</spid></root>";
      System.out.println("data=" + TFBUtils.getXmlElement(a, "record"));
   }
}
